package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.Goods;
import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.Type;
import com.cskaoyan.mall.service.GoodsService;
import com.cskaoyan.mall.service.GoodsServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * User: zsquirrel
 * Date: 2020/5/12
 * Time: 6:36 下午
 */
@WebServlet("/api/mall/index/*")
public class IndexServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/mall/index/", "");
        if("getType".equals(action)){
            getType(request, response);
        }else if("getGoodsByType".equals(action)){
            getGoodsByType(request, response);
        }else if("searchGoods".equals(action)){
            searchGoods(request, response);
        }
    }

    private void searchGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keyword = request.getParameter("keyword");
        List<Goods> goods = goodsService.searchGoods(keyword);
        response.getWriter().println(gson.toJson(Result.ok(goods)));
    }

    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<Goods> goods = goodsService.getGoodsByType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goods)));
    }

    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> type = goodsService.getType();
        response.getWriter().println(gson.toJson(Result.ok(type)));
    }
}
